/**
 * @param {number[]} position
 * @param {number[][]} terrain
 * @param {number[][]} obstacle
 * @return {number[][]}
 */
 var bicycleYard = function(position, terrain, obstacle) {
  const dirs = [[1, 0], [-1, 0], [0, 1], [0, -1]];
  const h = terrain.length;
  const w = terrain[0].length;
  let ret = [];
  let checked = new Array(h).fill(0).map(() => new Array(w).fill(0));
  checked[position[0]][position[1]] = 1;
  const valid = (x, y) => x >= 0 && x < h && y >= 0 && y < w;
  function dfs(speed, x, y, path) {
      for(let [dx, dy] of dirs) {
        cx = x + dx;
        cy = y + dy;
        if(valid(cx, cy)) {
          let s = speed + (terrain[x][y] - terrain[cx][cy] - obstacle[cx][cy]);
          if(s === 1 && !checked[cx][cy]) {
            ret.push([cx, cy]);
            return;
          }
          if(s > checked[cx][cy]) {
            checked[cx][cy] = s;
            dfs(s, cx, cy);
          } else {
            
          }
        }
      }
  }
  dfs(1, ...position, );
  return ret.sort((a, b) => a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]);
};

console.log(bicycleYard([0,1],
  [[63,91,53,6,70,29,1,86,31],[0,42,0,0,0,0,0,0,0],[0,0,0,0,0,74,77,94,8],[55,57,59,0,0,0,11,33,23],[58,27,51,0,0,56,10,24,7],[82,49,74,0,0,79,96,68,25],[72,51,67,0,58,59,81,52,64],[95,30,35,0,45,79,71,15,74]],
  [[21,7,31,16,33,39,25,12,4],[0,42,0,0,0,0,0,0,0],[0,0,0,0,0,19,14,43,30],[50,8,37,0,0,0,44,33,17],[5,12,29,0,0,30,2,33,40],[40,18,14,0,0,24,15,6,19],[10,3,40,0,39,38,16,44,48],[48,27,26,0,42,13,9,25,31]]))